{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 滑动平均模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import tensorflow as tf"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From D:\\ProgramData\\Anaconda3\\envs\\tf1.4-py3.7\\lib\\site-packages\\tensorflow\\python\\framework\\op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Colocations handled automatically by placer.\n"
     ]
    }
   ],
   "source": [
    "v1 = tf.Variable(0, dtype=tf.float32)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "step = tf.Variable(0, trainable=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "ema = tf.train.ExponentialMovingAverage(0.99, step)\n",
    "maintain_average_op = ema.apply([v1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0.0, 0.0]\n",
      "[5.0, 4.5]\n",
      "[10.0, 4.555]\n",
      "[10.0, 4.60945]\n"
     ]
    }
   ],
   "source": [
    "with tf.Session() as sess:\n",
    "    init_op = tf.global_variables_initializer()\n",
    "    sess.run(init_op)\n",
    "    \n",
    "    print(sess.run([v1, ema.average(v1)]))\n",
    "    \n",
    "    sess.run(tf.assign(v1, 5))\n",
    "    sess.run(maintain_average_op)\n",
    "    print(sess.run([v1, ema.average(v1)]))\n",
    "    \n",
    "    sess.run(tf.assign(step, 10000))\n",
    "    sess.run(tf.assign(v1, 10))\n",
    "    sess.run(maintain_average_op)\n",
    "    print(sess.run([v1, ema.average(v1)]))\n",
    "    \n",
    "    sess.run(maintain_average_op)\n",
    "    print(sess.run([v1, ema.average(v1)]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
